package com.jinzhi.jzweb.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzweb.dao.JazUserOrderDao;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.domain.param.UserAuntQuery;
import com.jinzhi.jzweb.domain.vo.AuntUserVO;
import com.jinzhi.jzweb.domain.vo.userAunt.UserAuntVO;
import com.jinzhi.jzweb.domain.vo.userAunt.UserVO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.dao.UserDao;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jinzhi.jzweb.dao.JazUserAuntDao;
import com.jinzhi.common.base.CoreServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2023-04-18 09:19:00 | Long</small>
 */
@Service
public class JazUserAuntServiceImpl extends CoreServiceImpl<JazUserAuntDao, JazUserAuntDO> implements JazUserAuntService {


    private final JazUserAuntDao jazUserAuntDao;

    private final UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private JazUserHouseService jazUserHouseService;

    @Autowired
    private  JazUserAuntService jazUserAuntService;

    /**
     * 积分明细
     */
    private final JazUserIntegralService jazUserIntegralService;

    /**
     * 标签
     */
    private final JazSysLabelService jazSysLabelService;

    /**
     * 项目类型
     */
    private final JazSysProjectService jazSysProjectService;

    /**
     * 字典表
     */
    private final DictService sysDictService;

    private final JazUserOrderDao jazUserOrderDao;


    public JazUserAuntServiceImpl(JazUserAuntDao jazUserAuntDao, UserDao userDao, JazUserIntegralService jazUserIntegralService, JazSysLabelService jazSysLabelService, JazSysProjectService jazSysProjectService, DictService sysDictService, JazUserOrderDao jazUserOrderDao) {
        this.jazUserAuntDao = jazUserAuntDao;
        this.userDao = userDao;
        this.jazUserIntegralService = jazUserIntegralService;
        this.jazSysLabelService = jazSysLabelService;
        this.jazSysProjectService = jazSysProjectService;
        this.sysDictService = sysDictService;
        this.jazUserOrderDao = jazUserOrderDao;
    }

    private static final Pattern IDCARD_PATTERN = Pattern.compile("^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$");

    public  boolean validateIDCard(String idCard) {
        Matcher matcher = IDCARD_PATTERN.matcher(idCard);
        return matcher.matches();
    }

    public  String extractBirthdate(String idCard) {
        if (idCard == null || idCard.length() != 18) {
            return null;
        }
        // 截取出生年月日（第7位到第14位）
//        return idCard.substring(6, 14);
        return idCard.substring(6, 10) + "-" + idCard.substring(10, 12) +"-"+ idCard.substring(12, 14);
    }
    @Override
    public AuntUserVO selAuntUserOne(AuntUserVO auntUserVO) {
        return jazUserAuntDao.selAuntUserOne(auntUserVO);
    }

    @Override
    public Page<AuntUserVO> selAuntUserListPage(AuntUserVO auntUserVO, int current, int size) {
        Page<AuntUserVO> page = new Page<>(current, size);
        List<AuntUserVO> auntUserVOS = jazUserAuntDao.selAuntUserListPage(page, auntUserVO);
        return page.setRecords(auntUserVOS);
    }
    /**
     * 新增月嫂信息
     * @param userAuntVO
     * @return
     */
    @Override
    @Transactional
    public Result<String> insertAunt(UserAuntVO userAuntVO) {
        if (userAuntVO == null){
            return Result.fail();
        }
        // 校验手机号是否已经被注册
        // 校验手机号是否注册
        List<UserDO> userDOList = userService.selectList(null);
        boolean isMobileExist = userDOList.stream()
                .anyMatch(existingUser -> existingUser.getMobile().equals(userAuntVO.getUserDO().getMobile()));
        if (isMobileExist){
            return Result.fail("手机号已注册");
        }
        //正常状态
        userAuntVO.getUserDO().setStatus(1);
        //审核状态：未完善
        userAuntVO.getUserDO().setState(3);
        // 设置类型
        userAuntVO.getUserDO().setType(1);
        //姓名赋予昵称
        userAuntVO.getUserDO().setNickname(userAuntVO.getUserDO().getName());
        // 校验身份证号
        if(StringUtil.notEmpty(userAuntVO.getUserDO().getIdNumber())){
            if (!validateIDCard(userAuntVO.getUserDO().getIdNumber())) {
                return Result.fail("身份证："+userAuntVO.getUserDO().getIdNumber()+"格式错误");
            }
            //获取出生年月
            userAuntVO.getJazUserAuntDO().setBirthDate(extractBirthdate(userAuntVO.getUserDO().getIdNumber()));
        }

        Integer userInteger = userDao.insert(userAuntVO.getUserDO());
        if(userInteger == 0){
            Result.fail("用户信息新增失败");
        }
        //与用户id绑定
        userAuntVO.getJazUserAuntDO().setSysUserid(userAuntVO.getUserDO().getId());
        //默认赋予接单手机号
        userAuntVO.getJazUserAuntDO().setPhone(userAuntVO.getUserDO().getMobile());

        insert(userAuntVO.getJazUserAuntDO());
        return Result.ok();
    }

    /**
     * 分页查询月嫂信息
     * @param userAuntQuery
     * @return
     */
    @Override
    public Page<JazUserAuntDO> getUserAuntPage(UserAuntQuery userAuntQuery) {
        Page<JazUserAuntDO> page = new Page<>(
                Optional.of(userAuntQuery.getCurr()).orElse(1),
                Optional.of(userAuntQuery.getPageSize()).orElse(10));
        Wrapper wrapper  = new EntityWrapper().
                like(StringUtil.notEmpty(userAuntQuery.getProjectId()),"project_id",userAuntQuery.getProjectId()).
                eq(Objects.nonNull(userAuntQuery.getSigningStatus()),"signing_status",userAuntQuery.getSigningStatus()).
                eq(Objects.nonNull(userAuntQuery.getAuntId()),"id",userAuntQuery.getAuntId()).
                eq(Objects.nonNull(userAuntQuery.getEnableStatus()),"enable_status",userAuntQuery.getEnableStatus()).
                andNew(userAuntQuery.getAuditStatus()== 1 && userAuntQuery.getAuditResult() == 0,
                        "(audit_status = {0} and audit_result ={1})",
                        userAuntQuery.getAuditStatus(),userAuntQuery.getAuditResult()).
                andNew(userAuntQuery.getAuditStatus()== 0 && userAuntQuery.getAuditResult() == 1,
                        "(audit_status = {0} or audit_result ={1})",
                        userAuntQuery.getAuditStatus(),userAuntQuery.getAuditResult())
                .orderBy("create_time",false);
        Page<JazUserAuntDO> jazUserAunts =  selectPage(page,wrapper);
        //查询用户信息
        List<Long> userIds = jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getSysUserid())).
                map(JazUserAuntDO::getSysUserid).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(userIds)){
            return jazUserAunts;
        }
        //拼接用户姓名
        List<UserDO> userDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds).
                like(StringUtil.notEmpty(userAuntQuery.getName()),"name",userAuntQuery.getName()));
        //用户信息不等于null
        if(!ObjectUtils.isEmpty(userDOS)){
            jazUserAunts.getRecords().forEach(a -> userDOS.forEach(b ->{
                if(Objects.equals(a.getSysUserid(),b.getId())){
                    a.setName(b.getName());
                }
            }));
        }
        //如果根据姓名查询查询
        if(StringUtil.notEmpty(userAuntQuery.getName())){
            jazUserAunts.setRecords(jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getName())).distinct().collect(Collectors.toList()));
        }

        //拼接学历
        List<UserDO> userEducationDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds).
                like(StringUtil.notEmpty(userAuntQuery.getEducation()),"education",userAuntQuery.getEducation()));
        //用户信息不等于null
        if(!ObjectUtils.isEmpty(userEducationDOS)){
            jazUserAunts.getRecords().forEach(a -> userEducationDOS.forEach(b ->{
                if(Objects.equals(a.getSysUserid(),b.getId())){
                    a.setEducation(b.getEducation());
                }
            }));
        }
        //如果根据学历查询
        if(StringUtil.notEmpty(userAuntQuery.getEducation())){
            jazUserAunts.setRecords(jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getEducation())).distinct().collect(Collectors.toList()));
        }

        //拼接手机号
        List<UserDO> userOrderPhoneDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds).
                like(StringUtil.notEmpty(userAuntQuery.getOrderPhone()),"order_phone",userAuntQuery.getOrderPhone()));
        //用户信息不等于null
        if(!ObjectUtils.isEmpty(userOrderPhoneDOS)){
            jazUserAunts.getRecords().forEach(a -> userOrderPhoneDOS.forEach(b ->{
                if(Objects.equals(a.getSysUserid(),b.getId())){
                    a.setOrderPhone(b.getOrderPhone());
                }
            }));
        }
        //如果根据手机号查询
        if(StringUtil.notEmpty(userAuntQuery.getOrderPhone())){
            jazUserAunts.setRecords(jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getOrderPhone())).distinct().collect(Collectors.toList()));
        }

        //拼接年龄
        if (StringUtil.notEmpty(userAuntQuery.getAge())){
            String[] split = userAuntQuery.getAge().split("-");
            List<UserDO> userAgeDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds).
                    between(userAuntQuery.getAge()!=null,"age",Integer.parseInt(split[0]),Integer.parseInt(split[1])));
            //用户信息不等于null
            if(!ObjectUtils.isEmpty(userAgeDOS)){
                jazUserAunts.getRecords().forEach(a -> userAgeDOS.forEach(b ->{
                    if(Objects.equals(a.getSysUserid(),b.getId())){
                        a.setAge(b.getAge().toString());
                    }
                }));
            }
            //如果根据手机号查询
            if(StringUtil.notEmpty(userAuntQuery.getAge())){
                jazUserAunts.setRecords(jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getAge())).distinct().collect(Collectors.toList()));
            }
        }else{
            List<UserDO> userAgeDOS = userDao.selectList(new EntityWrapper<UserDO>().in("id",userIds));
            //用户信息不等于null
            if(!ObjectUtils.isEmpty(userAgeDOS)){
                jazUserAunts.getRecords().forEach(a -> userAgeDOS.forEach(b ->{
                    if(Objects.equals(a.getSysUserid(),b.getId())){
                        if (b.getAge()!=null){
                            a.setAge(b.getAge().toString());
                        }
                    }
                }));
            }
            //如果根据手机号查询
            if(StringUtil.notEmpty(userAuntQuery.getAge())){
                jazUserAunts.setRecords(jazUserAunts.getRecords().stream().filter(a -> Objects.nonNull(a.getAge())).distinct().collect(Collectors.toList()));
            }
        }

        // 查询工作开始时间，工作结束时间
        jazUserAunts.getRecords().forEach(jazUserAuntDO ->{
            List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderDao.selectList(new EntityWrapper<JazUserOrderDO>()
                    .eq("signing_id", jazUserAuntDO.getSysUserid())
                    .in("status", Arrays.asList(1, 2)));
            if (jazUserOrderDOS.size()>0){
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                jazUserAuntDO.setStartTime(formatter.format(jazUserOrderDOS.get(0).getStartTime()));
                jazUserAuntDO.setEndTime(formatter.format(jazUserOrderDOS.get(0).getEndTime()));
            }else {
                jazUserAuntDO.setStartTime("");
                jazUserAuntDO.setEndTime("");
            }
        });

        //查询项目类型
        List<String> projectIds = jazUserAunts.getRecords().stream().filter(a ->Objects.nonNull(a.getProjectId()))
                .map(JazUserAuntDO::getProjectId).distinct().collect(Collectors.toList());
        if(ObjectUtils.isEmpty(projectIds)){
            return jazUserAunts;
        }
        List<String> projectIds1 = new ArrayList<>();
        for (int i = 0; i < projectIds.size(); i++) {
            projectIds1.addAll(Arrays.asList(projectIds.get(i).split(",")));
        }
        List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projectIds1));
        jazUserAunts.getRecords().forEach(a-> {
            a.setProjectName(jazSysProjectDOS.stream().filter(b -> Objects.nonNull(a.getProjectId())).
                    filter(b -> a.getProjectId().contains(b.getId().toString())).
                    map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        });
        return jazUserAunts;
    }
    /**
     * 根据月嫂id获取月嫂详细信息
     * @param id
     * @return
     */
    @Override
    public UserAuntVO getUserAuntById(Long id) {
        UserAuntVO userAuntVO = new UserAuntVO();
        //获取月嫂信息
        userAuntVO.setJazUserAuntDO(selectById(id));
        //获取用户信息
        UserDO userDO = userDao.selectById(userAuntVO.getJazUserAuntDO().getSysUserid());
        if (userDO == null) {
            return null;
        }
        StringBuffer buffer=new StringBuffer();
        if (StringUtil.notEmpty(userDO.getProvince())){
            buffer.append(userDO.getProvince());
        }
        if (StringUtil.notEmpty(userDO.getCity())){
            buffer.append(userDO.getCity());
        }
        if (StringUtil.notEmpty(userDO.getDistrict())){
            buffer.append(userDO.getDistrict());
        }
        if (StringUtil.notEmpty(userDO.getDetailedAddress())){
            buffer.append(userDO.getDetailedAddress());
        }
        userDO.setDetailedAddress(buffer.toString());
        userAuntVO.setUserDO(userDO);
        //查询标签信息
        if(StringUtil.notEmpty(userAuntVO.getJazUserAuntDO().getLabelId())){
            String[] labels = userAuntVO.getJazUserAuntDO().getLabelId().split(",");
            userAuntVO.setJazSysLabelDO(jazSysLabelService.selectList(new EntityWrapper<JazSysLabelDO>().in("id",labels)));
        }
        //查询项目类型
        if(StringUtil.notEmpty(userAuntVO.getJazUserAuntDO().getProjectId())){
            String[] projects = userAuntVO.getJazUserAuntDO().getProjectId().split(",");
            List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
            StringBuffer pro = new StringBuffer();
            userAuntVO.setJazSysProject(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
        }
        return userAuntVO;
    }

    /**
     * 修改月嫂信息
     * @param userAuntVO
     * @return
     */
    @Override
    @Transactional
    public UserAuntVO updateUserAnut(UserAuntVO userAuntVO){
        //修改用户信息
        userDao.updateById(userAuntVO.getUserDO());
        //修改月嫂信息
        JazUserAuntDO jazUserAuntDO = userAuntVO.getJazUserAuntDO();
        // 校验身份证号
        if(null!=userAuntVO.getUserDO().getIdNumber()){
            if (!validateIDCard(userAuntVO.getUserDO().getIdNumber())) {
                return null;
            }
            //获取出生年月
            jazUserAuntDO.setBirthDate(extractBirthdate(userAuntVO.getUserDO().getIdNumber()));
        }
        // 设置状态为待审核
        jazUserAuntDO.setAuditStatus(0);
        updateById(jazUserAuntDO);
        return userAuntVO;
    }

    /**
     * 更改月嫂订单完成数量
     * */
    @Override
    public void updateUserAuntOrderCount(JazUserAuntDO jazUserAuntDO) {
        jazUserAuntDao.updateUserAuntOrderCount(jazUserAuntDO);
    }


    /**
     * 月嫂简历-刷新一次使用20积分-每天只能刷新一次-刷新前判断是否积分足够不过返回积分不够提示
     * */
    @Override
    public int curriculumVitaeRefresh() {
                //查询出用户信息
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
        //查询用户积分是否足够
        if ( Double.valueOf(userDO.getCurrentPoints()) < 20){//如果现有积分小于20那么提示积分不够
                return 0;//返回0表示积分不够
        }else {//如果积分大于20，可以刷新一次
            userDO.setCurrentPoints(String.valueOf(Double.valueOf( userDO.getCurrentPoints()) - 20)); //扣除20积分
            userDO.setRefreshTime(new Date());//刷新时间
            userDO.setRefresh(1);//奖励是否已刷新，1为已刷新
            userDO.setSortStatus(1);//将置顶状态变为1
            userService.updateById(userDO);
            JazUserIntegralDO zdUserIntegralDO = new JazUserIntegralDO();
            zdUserIntegralDO.setIntegralDetail("-20"); //积分
            zdUserIntegralDO.setSysUserid(userDO.getId()); //用户id
            zdUserIntegralDO.setIntegralTime(new Date()); //时间
            zdUserIntegralDO.setIntegralWay("简历置顶"); //用途
            zdUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
            jazUserIntegralService.insert(zdUserIntegralDO);
            return 1;//成功返回一
        }
    }


    @Override
    public List<JazUserAuntDO> getSort(UserDO userDO) {
        List<JazUserAuntDO> sort = jazUserAuntDao.getSort(userDO);
        return sort;
    }


    /**
     * 根据当前时间判断今天刷新按钮是否已经使用过
     * */
    @Override
    public  int whetherrefresh() {
        //用户信息
        UserDO getUser = JWTUtil.getUser();
        getUser = userService.selectById(getUser.getId());
        if (getUser.getRefreshTime() == null) {//如果上次刷新时间为空，那么说明没有刷新过，返回1，表示能刷新
            return 1; //能点
        }
        Date date = new Date();
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String str = sdf.format(date);//当前时间（年月日）
        DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String str2 = sdf2.format(getUser.getRefreshTime());//上次刷新时间
        try {
            Date d1 = sdf.parse(str);//当前时间
            Date d2 = sdf.parse(str2);//数据库刷新时间
            long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);//小时数
            if (str.equals(str2) && getUser.getRefresh().equals(1)) {//如果当前时间与数据库时间相同，同时刷新状态为1同时距离上次刷新未超过24小时，那么说明已经刷新过
                return 0;//按钮置灰
            }
//            else if ( hours <= 24) {//如果上次刷新时间和现在时间不同，同时他们相差时间小于24个小时，那么不可以刷新
//                return 0;//按钮置灰
//            }
            else if (getUser.getRefresh().equals(1) && hours <= 24) {//如果刷新状态为1说明已经刷新过，同时上次刷新时间小于24小时那么也不可以刷新
                return 0;//按钮置灰
            } else {//否则没有刷新过，更改刷新状态
                UserDO userDO = new UserDO();
                userDO.setId(getUser.getId());
                userDO.setRefresh(0);
                userService.updateById(userDO);
                return 1;//能点
            }
        } catch (Exception e) {
                    return 5;
        }

    }

    /**
     * 根据id修改启用状态
     * @param jazUserAuntDO
     * @return
     */
    @Override
    public Result updateUserAnutStatus(JazUserAuntDO jazUserAuntDO) {
        JazUserAuntDO jazUserAuntDO1 = this.selectById(jazUserAuntDO.getId());
        if (jazUserAuntDO1==null) {
            return Result.fail();
        }
        jazUserAuntDO1.setEnableStatus(jazUserAuntDO.getEnableStatus());
        boolean update = this.updateById(jazUserAuntDO1);
        return update?Result.ok():Result.fail();
    }

    /***
     * 查询所有月嫂信息
     * @return
     */
    @Override
    public List<UserVO> getUserAunt() {
        List<UserVO> userVOList = new ArrayList<>();
        // 获取已通过审核的阿姨的信息
        List<JazUserAuntDO> jazUserAuntDOList = this.selectList(new EntityWrapper<JazUserAuntDO>()
                .eq("audit_status",1).eq("audit_result",0).eq("enable_status",1));
        // 获取所有住宿列表
        List<Long> list = new ArrayList<>();
        List<JazUserHouseDO> jazUserHouseDOS = jazUserHouseService.selectList(null);
        jazUserHouseDOS.stream().forEach(jazUserHouseDO -> {
            list.add(jazUserHouseDO.getSysUserid());
        });
        // 获取所有的阿姨的用户表id
        jazUserAuntDOList.stream().forEach(userAunt->{
            UserVO userVO = new UserVO();
            UserDO userDO = userService.selectById(userAunt.getSysUserid());
            userVO.setSex(userDO.getSex());
            userVO.setName(userDO.getName());
            userVO.setSysUserid(userDO.getId());
            userVO.setMobile(userDO.getMobile());
            userVO.setProjectId(userAunt.getProjectId());
            if(StringUtil.notEmpty(userAunt.getProjectId())){
                String[] projects = userAunt.getProjectId().split(",");
                List<JazSysProjectDO>  jazSysProjectDOS = jazSysProjectService.selectList(new EntityWrapper<JazSysProjectDO>().in("id",projects));
                StringBuffer pro = new StringBuffer();
                userVO.setProjectName(jazSysProjectDOS.stream().map(JazSysProjectDO::getName).collect(Collectors.joining(",")));
            }
            userVOList.add(userVO);
        });
        // 过滤出已经住宿的信息
        List<UserVO> voList = userVOList.stream().filter(userVO -> !list.contains(userVO.getSysUserid())).collect(Collectors.toList());

        return voList;
    }


}
